﻿module Sustainalytics.Portfolio {
    import Common = Sustainalytics.Common;

    export class SubscribeToPortfolioService implements ISubscribeToPortfolioService {
        private $q: ng.IQService;
        private $http: ng.IHttpService;
        private notificationFactory: Common.INotificationFactory;
        private staticObjects: Common.IStaticObjects;
        private urlBase: string;

        // Ctor.
        public constructor($q: ng.IQService, $http: ng.IHttpService, notificationFactory: Common.INotificationFactory, staticObjects: Common.IStaticObjects) {
            this.$q = $q;
            this.$http = $http;
            this.notificationFactory = notificationFactory;
            this.staticObjects = staticObjects;
            this.urlBase = staticObjects.portfolioBaseUrl;
        }

        // show error message for a given error code
        private showError(err) {
            var ctx = this;
            if (err && err['errorCode'])
                ctx.notificationFactory.error('', ctx.staticObjects.getErrorMesageByStatusCode(err['errorCode'], err['errorCode']));
        }

        private showMessage(msg) {
            var ctx = this;
            ctx.notificationFactory.success(msg);
        }

        public getAllSubscriptionForUser(userId: string, accountId: string) {
            var ctx = this;
            var def = this.$q.defer();

            var params = $.param({
                userId: userId,
                accountId: accountId
            });

            var url = ctx.urlBase + "/api/v1/subscribetoportfolio?" + params;

            var promise = this.$http.get(url);

            promise.success(
                data => {
                    def.resolve(data);
                }).error(
                err => {
                    this.showError(err);
                    def.reject();
                });

            return def.promise;
        }

        public getSharedAndMyPortfolios(userId: string, accountId: string): ng.IPromise<{}> {
            var def = this.$q.defer();

            var params = $.param({
                userId: userId,
                accountId: accountId,
                getAllPortfolios: true
            });

            var url: string = this.urlBase + '/api/v1/subscribetoportfolio?' + params;
            //var httpConfig: ng.IRequestConfig = { method: 'PATCH', url: url};
            var promise = this.$http.get(url); //(httpConfig);

            promise.success(
                data => {
                    def.resolve(data);
                }).error(
                err => {
                    this.showError(err);
                    def.reject();
                });

            return def.promise;
        }

        public insertSubscription(item: SubscribeToPortfolio): ng.IPromise<{}> {
            var ctx = this;
            var def = this.$q.defer();

            console.log(item);

            var url: string = this.urlBase + '/api/v1/subscribetoportfolio';// + params;

            var promise: ng.IHttpPromise<{}> = this.$http.post(url, item);

            promise.success(function (data) {
                ctx.showMessage("Subscription added successfully!");
                def.resolve(data);
            })
                .error(function (err) {
                ctx.showError(err);
                def.reject();
            })

            return def.promise;
        }

        public editSubscription(item: SubscribeToPortfolio): ng.IPromise<{}> {
            var ctx = this;
            var def = this.$q.defer();

            var url: string = this.urlBase + '/api/v1/subscribetoportfolio';

            var promise: ng.IHttpPromise<{}> = this.$http.put(url, item);

            promise.success(function (data) {
                ctx.showMessage("Subscription edited successfully!");
                def.resolve(data);
            })
                .error(function (err) {
                ctx.showError(err);
                def.reject();
            })

            return def.promise;
        }

        public deleteSubscription(id: string, userId: string, accountId: string): ng.IPromise<{}> {
            var ctx = this;
            var def = this.$q.defer();

            var params = $.param({
                id: id,
                userId: userId,
                accountId: accountId
            });

            var url: string = this.urlBase + '/api/v1/subscribetoportfolio/'+ id +'?' + params;

            var promise: ng.IHttpPromise<{}> = this.$http['delete'](url);

            promise.success(function (data) {
                //ctx.showMessage("Subscription deleted successfully!");
                def.resolve(data);
            })
                .error(function (err) {
                ctx.showError(err);
                def.reject();
            })
            return def.promise;
        }

        public updateStatusSubscription(id: string, userId: string, accountId: string, status: boolean) {
            var ctx = this;
            var def = this.$q.defer();

            var params = $.param({
                userId: userId,
                accountId: accountId,
                status: status
            });

            var url: string = this.urlBase + '/api/v1/subscribetoportfolio/'+ id+ '?' + params;
            var httpConfig: ng.IRequestConfig = { method: 'PATCH', url: url };
            var promise = this.$http(httpConfig);

            promise.success(
                function (data) {
                    def.resolve(data);
                }).error(
                function (err) {
                    ctx.showError(err);
                    def.reject();
                })

            return def.promise;
        }
    }

    // register service with Portfolio Angular module
    angular.module(portfolioModuleName).service('SubscribeToPortfolioService',
        ['$q', '$http', 'notificationFactory', 'staticObjects', SubscribeToPortfolioService]);
}